# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import csv, scrapy

import DoubanSpider
from items import MovieBaseItem
from items import MovieAwardItem
from items import MovieCriticsItem


class DoubanPipeline(object):
    def __init__(self):
        self.csv_file1 = open('movie_base.csv', 'w', newline='', encoding='utf-8')
        self.writer1 = csv.writer(self.csv_file1)
        self.csv_file2 = open('movie_award.csv', 'w', newline='', encoding='utf-8')
        self.writer2 = csv.writer(self.csv_file2)
        self.csv_file3 = open('movie_review.csv', 'w', newline='', encoding='utf-8')
        self.writer3 = csv.writer(self.csv_file3)
        self.writer1.writerow(
            ['电影名', '排名', '基本信息', '得分', '评论数', '引文'])
        self.writer2.writerow(
            ['奖项名', '所获奖项名', '获奖人'])
        self.writer3.writerow(
            ['影评人', '打分', '评论时间', '影评标题', '影评内容'])

    def process_item(self, item, spider):
        if isinstance(item, DoubanSpider.items.MovieBaseItem):
            line = [item['movie_name'], item['movie_ranking'], item['movie_info'], item['movie_score'],
                    item['movie_comment_num'], item['movie_quote']]
            print(line)
            self.writer1.writerow(line)
        elif isinstance(item, DoubanSpider.items.MovieAwardItem):
            line = [item['awards_name'], item['award_name'], item['award_people']]
            self.writer2.writerow(line)
        elif isinstance(item, DoubanSpider.items.MovieCriticsItem):
            line = [item['critic_name'], item['critic_score'], item['critic_time'], item['critic_title'],
                    item['critic_content']]
            self.writer3.writerow(line)

        return item

    def close_spider(self):
        self.csv_file1.close()
        self.csv_file2.close()
        self.csv_file3.close()
